/*
 *  DbExchangeTableEntry.cpp
 *  StrategyInspector
 *
 *  Created by jiro on 12/08/07.
 *  Copyright 2012 jiro music. All rights reserved.
 *
 */

#include "DbExchangeTableEntry.h"

#include "DbUtility.h"
#include "../../Commons.h"

DbExchangeTableEntry::DbExchangeTableEntry()
{
}

DbExchangeTableEntry::DbExchangeTableEntry( const std::vector< const char* >& values )
{
	code			= [ NSString stringWithCString: values[ 0 ] encoding: NSUTF8StringEncoding ];
	exchangeDate	= [ DbUtility convertIsoStdDateCStringToNSDate: values[ 1 ] ];
	openPrice		= atof( values[ 2 ] );
	closePrice		= atof( values[ 3 ] );
	highPrice		= atof( values[ 4 ] );
	lowPrice		= atof( values[ 5 ] );
}

DbExchangeTableEntry::~DbExchangeTableEntry()
{
}

double DbExchangeTableEntry::getVolatilityOf( const std::vector< DbExchangeTableEntry >& exchangeEntries, PriceField::Type type )
{
	double adjust = 1000;
	double rateSum = 0.0;
	int count = exchangeEntries.size();
	for ( int i = 1; i < count; i++ )
	{
		const DbExchangeTableEntry& e1 = exchangeEntries[ i - 1 ];
		const DbExchangeTableEntry& e2 = exchangeEntries[ i ];
		double rate = e2.getPrice( type ) / e1.getPrice( type );
		if ( rate > 1 )
		{
			rate -= 1.0;
		}
		else if ( rate < 1 )
		{
			rate = 1 - rate; 
		}
		rateSum += adjust * rate;
	}
	double volatility = rateSum / ( count - 1 );
	volatility /= adjust;
	return volatility;

}

double DbExchangeTableEntry::getPrice( PriceField::Type type ) const
{
	switch ( type )
	{ 
	case PriceField::Type_StartPrice:
		return openPrice;
	case PriceField::Type_EndPrice:
		return closePrice;
	case PriceField::Type_HighestPrice:
		return highPrice;
	case PriceField::Type_LowestPrice:
		return lowPrice;
	case PriceField::Type_MiddleBetweenStartAndEnd:
		return ( openPrice + closePrice ) / 2.0;
	case  PriceField::Type_MiddleBetweenHighAndLow:
		return ( highPrice + lowPrice ) / 2.0;
	default: 
		throw ( [ NSException  exceptionWithName: kText_ApplicationErrorException reason: @"" userInfo: nil ] );
	}

}

double DbExchangeTableEntry::getPriceWidth() const
{
	return highPrice - lowPrice;
}

double DbExchangeTableEntry::getOpenPrice() const
{
	return openPrice;
}

double DbExchangeTableEntry::getClosePrice() const
{
	return closePrice;
}

double DbExchangeTableEntry::getHighPrice() const
{
	return highPrice;
}

double DbExchangeTableEntry::getLowPrice() const
{
	return lowPrice;
}

NSString* DbExchangeTableEntry::queryInsertValue() const
{
	NSString* s = [ NSString stringWithFormat: @"( '%@', '%@', %f, %f, %f, %f )",
		code, exchangeDate, openPrice, highPrice, lowPrice, closePrice ];
	return s;
}

NSString* DbExchangeTableEntry::queryInsert() const
{
	NSString* s = [ NSString stringWithFormat: @"insert into %@ values %@;",
		tableName(), queryInsertValue() ];
	return s;
}
